import numpy as np


def sigmoid(x):
    return 1 / (1 + np.exp(-x))


def xywh2xyxy(boxes):
    """
    xywh转xyxy
    :param boxes: 输入框
    :return: 转好的框
    """
    boxes[:, :, 0] = boxes[:, :, 0] - boxes[:, :, 2] / 2
    boxes[:, :, 1] = boxes[:, :, 1] - boxes[:, :, 3] / 2
    boxes[:, :, 2] = boxes[:, :, 0] + boxes[:, :, 2]
    boxes[:, :, 3] = boxes[:, :, 1] + boxes[:, :, 3]
    return boxes


def iou(box1, box2):
    """
    计算iou, 只接受xyxy格式的框
    :param box1: 框1
    :param box2: 框2
    :return: 交并比
    """
    box1_x1 = box1[0]
    box1_y1 = box1[1]
    box1_x2 = box1[2]
    box1_y2 = box1[3]

    box2_x1 = box2[0]
    box2_y1 = box2[1]
    box2_x2 = box2[2]
    box2_y2 = box2[3]

    x1 = np.max([box1_x1, box2_x1])
    y1 = np.max([box1_y1, box2_y1])
    x2 = np.min([box1_x2, box2_x2])
    y2 = np.min([box1_y2, box2_y2])

    intersection = np.max([0, x2 - x1]) * np.max([0, y2 - y1])

    box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1))
    box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1))

    return intersection / (box1_area + box2_area - intersection + 1e-6)
